<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-sunset.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-sunset.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-sunset.png?v=7.4.0">
  <link rel="mask-icon" href="/images/logo-sunset.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="需求分析在我们以往做过的各个项目中，用户为了给单据做归档，尤其是根据打印后的纸质单据做归档，往往要求单据号要特定的规则，有的要有流水号，有的要随机号，有的单据需要带前缀，有的要带后缀。举个例子，我们要做一个送货单的单据号生成服务，希望送货单是由前缀D + 日期 + 流水号的方式组成，例如D20190926000001、D20190926000002、D20190926000003。    对于各种">
<meta name="keywords" content="发号机 乐观锁 策略模式">
<meta property="og:type" content="article">
<meta property="og:title" content="手写一个规则可配置的高并发的发号机">
<meta property="og:url" content="http://yoursite.com/2019/09/26/手写一个永不重复的发号机/index.html">
<meta property="og:site_name" content="志泳的博客-学习、分享、成长">
<meta property="og:description" content="需求分析在我们以往做过的各个项目中，用户为了给单据做归档，尤其是根据打印后的纸质单据做归档，往往要求单据号要特定的规则，有的要有流水号，有的要随机号，有的单据需要带前缀，有的要带后缀。举个例子，我们要做一个送货单的单据号生成服务，希望送货单是由前缀D + 日期 + 流水号的方式组成，例如D20190926000001、D20190926000002、D20190926000003。    对于各种">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://www.plantuml.com/plantuml/svg/yqnnJyrBBKeioIzopiyhAShFoKajKiZNrLNmHCYu9IO3oKekJ245aBhW4g1GQdgbrTEEsKztxq9MXcGcYieN6vgVJrd1nQMWW2IgO5C3j3SuBx_SBISnEnKkZ4sLOsb9lcTUSb5gRcfU2OfAx39WJIv0DgQK0W00">
<meta property="og:image" content="http://www.plantuml.com/plantuml/svg/TP3D2e9058NtFeKlq0kuw5sYNBGDQLrM89bAP48gKf0KGJ-kPjAYbvaxCwrwXHGZjP_DvN3ldFCDXs0NnYlg6-aKQtKHh2bOYFgnbAfxhm_6d1e75YKGw8_BX1yHZLHk8h2S_9I-5XfDfTrjA7BX5jug2-MR8MWBjdVOF0GKWgbAT7dEp1_fUUu8aUkCkSFyMZOBpOwSSIgxx_HFvWzQZgAQ0ve7ILn62Vy_B_7JWDdR2hBQ6h_Pu0K4wmJt2DvbWBMRYgAiQZefzVyoCmz3R1U6bloZtoS0">
<meta property="og:updated_time" content="2019-10-23T15:28:02.987Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="手写一个规则可配置的高并发的发号机">
<meta name="twitter:description" content="需求分析在我们以往做过的各个项目中，用户为了给单据做归档，尤其是根据打印后的纸质单据做归档，往往要求单据号要特定的规则，有的要有流水号，有的要随机号，有的单据需要带前缀，有的要带后缀。举个例子，我们要做一个送货单的单据号生成服务，希望送货单是由前缀D + 日期 + 流水号的方式组成，例如D20190926000001、D20190926000002、D20190926000003。    对于各种">
<meta name="twitter:image" content="http://www.plantuml.com/plantuml/svg/yqnnJyrBBKeioIzopiyhAShFoKajKiZNrLNmHCYu9IO3oKekJ245aBhW4g1GQdgbrTEEsKztxq9MXcGcYieN6vgVJrd1nQMWW2IgO5C3j3SuBx_SBISnEnKkZ4sLOsb9lcTUSb5gRcfU2OfAx39WJIv0DgQK0W00">
  <link rel="canonical" href="http://yoursite.com/2019/09/26/手写一个永不重复的发号机/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>手写一个规则可配置的高并发的发号机 | 志泳的博客-学习、分享、成长</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?aff336890e85bc8e76e40e879cca6bf8";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">志泳的博客-学习、分享、成长</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/09/26/手写一个永不重复的发号机/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Jimmy Wong">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="志泳的博客-学习、分享、成长">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">手写一个规则可配置的高并发的发号机

          
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2019-09-26 16:53:56" itemprop="dateCreated datePublished" datetime="2019-09-26T16:53:56+00:00">2019-09-26</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-10-23 15:28:02" itemprop="dateModified" datetime="2019-10-23T15:28:02+00:00">2019-10-23</time>
              </span>
            
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="需求分析"><a href="#需求分析" class="headerlink" title="需求分析"></a>需求分析</h1><p>在我们以往做过的各个项目中，用户为了给单据做归档，尤其是根据打印后的纸质单据做归档，往往要求单据号要特定的规则，有的要有流水号，有的要随机号，有的单据需要带前缀，有的要带后缀。举个例子，我们要做一个送货单的单据号生成服务，希望送货单是由前缀D + 日期 + 流水号的方式组成，例如D20190926000001、D20190926000002、D20190926000003。    </p><p>对于各种单据号的生成，其实很多是很类似的，我们需要写一个通用发号机功能，并作为一个公共服务开放出来，可以支持各种发号的规则，同时支持高并发的情况。</p><p>该文章的所有源码请参考如下：<br><a href="https://github.com/hzy2009/id-generator" target="_blank" rel="noopener">https://github.com/hzy2009/id-generator</a></p><a id="more"></a>


<h1 id="系统设计"><a href="#系统设计" class="headerlink" title="系统设计"></a>系统设计</h1><p>目前需求有3个关键的点:  </p>
<ol>
<li>发号机可以通过restful的方式把服务开放出来。</li>
<li>各种单据号规则要灵活可配置。</li>
<li>号码不能重复，尤其是流水号的设计，流水号是有顺序的号码，当出现并发情况的时候，保证流水号要保持顺序且不重复。  </li>
</ol>
<p><strong><em>使用springcloud 把接口作为服务的方式开放出来</em></strong>  </p>
<p>对于怎样搭建springcloud，这里不是重点就不展开说。</p>
<p><strong><em>使用策略模式，灵活支持各种不同的号码规则策略</em></strong>  </p>
<p>由于单据号的生成规则，会有多个规则，我们先设计一个规则策略接口，以便产生有多种规则策略的实现。并且通过一个策略工厂，根据不同的单据类型产生不同的单据规则。但业务发请求来获取单据号是，发号机调用策略工厂获取单据规则策略，并通过单据规则策略生成单据号。  </p>
<img src="http://www.plantuml.com/plantuml/svg/yqnnJyrBBKeioIzopiyhAShFoKajKiZNrLNmHCYu9IO3oKekJ245aBhW4g1GQdgbrTEEsKztxq9MXcGcYieN6vgVJrd1nQMWW2IgO5C3j3SuBx_SBISnEnKkZ4sLOsb9lcTUSb5gRcfU2OfAx39WJIv0DgQK0W00">  

<img src="http://www.plantuml.com/plantuml/svg/TP3D2e9058NtFeKlq0kuw5sYNBGDQLrM89bAP48gKf0KGJ-kPjAYbvaxCwrwXHGZjP_DvN3ldFCDXs0NnYlg6-aKQtKHh2bOYFgnbAfxhm_6d1e75YKGw8_BX1yHZLHk8h2S_9I-5XfDfTrjA7BX5jug2-MR8MWBjdVOF0GKWgbAT7dEp1_fUUu8aUkCkSFyMZOBpOwSSIgxx_HFvWzQZgAQ0ve7ILn62Vy_B_7JWDdR2hBQ6h_Pu0K4wmJt2DvbWBMRYgAiQZefzVyoCmz3R1U6bloZtoS0">   

<p><strong><em>使用Redis的INCR的命令，保证流水号连贯不重复</em></strong>  </p>
<p>由于流水号是需要单据号是要连贯的，所以要记录当前流水号是什么，才能知道下一个号是什么。因此我们需要把单据的流水号持久化，当服务重启的时候，不用担心会丢失当前的流水号，导致无法往下接。这里我们先采用redis作为持久化的数据库。考虑到并发的情况，我们通过INCR的方式来更新最新的流水号。</p>
<h1 id="具体实现"><a href="#具体实现" class="headerlink" title="具体实现"></a>具体实现</h1><p>根据以上的设计思路，项目结构如下：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">|-- generator</span><br><span class="line">    |-- IdGeneratorApplication.java          //启动类</span><br><span class="line">    |-- IdGeneratorConfiguration.java        //配置类</span><br><span class="line">    |-- SpringContextHolder.java             //工具类</span><br><span class="line">    |-- client</span><br><span class="line">       |   |-- IdGeneratorService.java       //接口服务定义</span><br><span class="line">       |-- controller</span><br><span class="line">       |   |-- IdGeneratorController.java    //接口服务实现</span><br><span class="line">       |-- model</span><br><span class="line">       |-- service</span><br><span class="line">           |-- IdGeneratorFactory.java       //规则策略工厂</span><br><span class="line">           |-- IdStrategy.java               //发号机接口</span><br><span class="line">           |-- impl</span><br><span class="line">               |-- AutoIncrementStrategy.java  //流水号(自增Id)规则实现</span><br><span class="line">               |-- DateIncrementStrategy.java  //日期加流水号(自增Id)规则实现</span><br><span class="line">               |-- RandomStrategy.java         //日期加随机码规则实现</span><br><span class="line">               |-- SnowFlakeStrategy.java      //雪花ID规则实现</span><br></pre></td></tr></table></figure>

<h2 id="服务接口的定义"><a href="#服务接口的定义" class="headerlink" title="服务接口的定义"></a>服务接口的定义</h2><p>根据之前需求的理解，对发号机的接口做了简单定义，里面包含以下方法：  </p>
<ul>
<li>makeId(): 根据单据的类型，生成下一个单据号  </li>
<li>makeIds(…): 根据单据的类型，单据号的需求数量，生成相应的一批单据号。  </li>
</ul>
<p>代码如下：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">public interface IdGeneratorService &#123;</span><br><span class="line"></span><br><span class="line">    public String makeId(String idType);</span><br><span class="line"></span><br><span class="line">    public Queue&lt;String&gt; makeIds(String idType, int quantity);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="单据规则策略接口的定义"><a href="#单据规则策略接口的定义" class="headerlink" title="单据规则策略接口的定义"></a>单据规则策略接口的定义</h2><p>对于单据规则接口，只需要一个方法就可以。  </p>
<ul>
<li>makeIds(…) 根据单据号的需求数量，生成相应的一批单据号。  </li>
</ul>
<p>代码如下：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public interface IdStrategy &#123;</span><br><span class="line"></span><br><span class="line">    public Queue&lt;String&gt; makeIds(int quantity);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="单据号规则的工厂类"><a href="#单据号规则的工厂类" class="headerlink" title="单据号规则的工厂类"></a>单据号规则的工厂类</h2><p>工厂类中，增加一个build方法，根据单据类型生成一个对应单据号规则。为了避免每次都生成一个新的对象，工厂中加了一个Map类做缓存，缓存单据类型和类型对应的单据规则。考虑到会出现并发的情况，对该Map做了一个锁的控制。在这里，各个单据类型与单据规则的对应关系，目前是写死在代码上，通过switch来做对应的关系。在实际的情况中应该是通过数据库来保存这些信息。代码如下：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">public class IdGeneratorFactory &#123;</span><br><span class="line">    </span><br><span class="line">    private static Logger logger = LoggerFactory.getLogger(IdGeneratorFactory.class);</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 单据类型与规则策略的Map</span><br><span class="line">     */</span><br><span class="line">    private static Map&lt;String, IdStrategy&gt; typeAndStrategyMap = new Hashtable&lt;&gt;();</span><br><span class="line">    </span><br><span class="line">    public static IdStrategy bulid(String idType)&#123;</span><br><span class="line">        </span><br><span class="line">        IdStrategy strategy = typeAndStrategyMap.get(idType);</span><br><span class="line">        </span><br><span class="line">        if (strategy == null) &#123;</span><br><span class="line">            synchronized (typeAndStrategyMap) &#123;</span><br><span class="line">                if (typeAndStrategyMap.get(idType) == null) &#123;</span><br><span class="line">                    strategy = bulidByType(idType);</span><br><span class="line">                    typeAndStrategyMap.put(idType, strategy);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        strategy = typeAndStrategyMap.get(idType);</span><br><span class="line">        logger.trace(&quot;根据单据类型[&#123;&#125;],获取单据规则[&#123;&#125;]&quot;, idType, strategy.getClass());</span><br><span class="line">        return strategy;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private static IdStrategy bulidByType(String idType) &#123;</span><br><span class="line">        switch (idType) &#123;</span><br><span class="line">        case &quot;AUTOINCREMENT&quot;: </span><br><span class="line">            // 如果是采购单</span><br><span class="line">            return new AutoIncrementStrategy(idType);</span><br><span class="line">        case &quot;DATEINCREMENT&quot;:</span><br><span class="line">            // 如果是送货单</span><br><span class="line">            return new DateIncrementStrategy(idType);</span><br><span class="line">        case &quot;RANDOM&quot;:</span><br><span class="line">            // 如果是对账单</span><br><span class="line">            return new RandomStrategy();</span><br><span class="line">        case &quot;SNOWFLAKE&quot;:</span><br><span class="line">            // 如果是文件的编码获取</span><br><span class="line">            return new SnowFlakeStrategy();</span><br><span class="line">        default:</span><br><span class="line">            logger.error(&quot;单据类型[&#123;&#125;],没有匹配的单据规则策略&quot;, idType);</span><br><span class="line">            throw new RuntimeException(&quot;该单据类型没有匹配的单据规则策略&quot;);</span><br><span class="line">        &#125;        </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private IdGeneratorFactory() &#123;</span><br><span class="line">        super();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="随机Id的规则策略实现"><a href="#随机Id的规则策略实现" class="headerlink" title="随机Id的规则策略实现"></a>随机Id的规则策略实现</h2><p>在了解雪花算法之前，我们的随机ID的是通过使用日期 + 随机码组成32位的Id。简单点就是 yyyyMMddHHmmss-{7位随机码}。代码如下：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line">public class RandomStrategy implements IdStrategy &#123;</span><br><span class="line">    </span><br><span class="line">    private static SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;yyyyMMddHHmmss&quot;);</span><br><span class="line">    private static List&lt;String&gt; code = new ArrayList&lt;&gt;();</span><br><span class="line">    private static Random random = new Random();</span><br><span class="line"></span><br><span class="line">    static &#123;</span><br><span class="line">        //向集合中添加0-9 a-z A-Z</span><br><span class="line">        //添加0~9</span><br><span class="line">        for (int i = 0; i &lt; 10; i++) &#123;</span><br><span class="line">            code.add(String.valueOf(i));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        //添加大小写字母</span><br><span class="line">        for (int i = 0; i &lt; 26; i++) &#123;</span><br><span class="line">            code.add(String.valueOf((char) (65 + i)));</span><br><span class="line">            code.add(String.valueOf((char) (97 + i)));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    @Override</span><br><span class="line">    public Queue&lt;String&gt; makeIds(int quantity) &#123;</span><br><span class="line">        String dateStr = dateFormat.format(new Date());</span><br><span class="line">        Queue&lt;String&gt; idList = new LinkedBlockingQueue&lt;&gt;(quantity);</span><br><span class="line">        </span><br><span class="line">        while (idList.size() &lt; quantity) &#123;</span><br><span class="line">            StringBuffer uuid = new StringBuffer();</span><br><span class="line">            uuid.append(dateStr);</span><br><span class="line">            uuid.append(&apos;-&apos;);</span><br><span class="line">            uuid.append(getEightRandomCode());</span><br><span class="line">            idList.add(uuid.toString());</span><br><span class="line">        &#125;</span><br><span class="line">        return idList;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取八位随机码</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    private static String getEightRandomCode() &#123;</span><br><span class="line">        StringBuilder sb = new StringBuilder();</span><br><span class="line">        for (int i = 0; i &lt; 8; i++) &#123;</span><br><span class="line">            //通过随机数，从集合中得到相应的字符</span><br><span class="line">            sb.append(code.get(random.nextInt(code.size())));</span><br><span class="line">        &#125;</span><br><span class="line">        return sb.toString();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对比于雪花Id上面的规则，虽然有点简陋但是已经满足基本的需求。但如果是在分布式情况下是没办法保证Id不重复，一方面时间没办法同步，另外一方面虽然是用Set排重，但是多台应用件各自的Set不一样，无法排重。  </p>
<h2 id="雪花Id的规则策略实现"><a href="#雪花Id的规则策略实现" class="headerlink" title="雪花Id的规则策略实现"></a>雪花Id的规则策略实现</h2><p>以下是雪花Id生成策略，基于网上的一些代码修改:<a href="https://www.jianshu.com/p/3a2a61361512" target="_blank" rel="noopener">雪花算法生成分布式ID</a>。代码如下:  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br></pre></td><td class="code"><pre><span class="line">public class SnowFlakeStrategy implements IdStrategy &#123;</span><br><span class="line">    </span><br><span class="line">    private static final Logger logger = LoggerFactory.getLogger(SnowFlakeStrategy.class);</span><br><span class="line"></span><br><span class="line">    private final static long TWEPOCH = 1288834974657L;</span><br><span class="line"></span><br><span class="line">    // 机器标识位数</span><br><span class="line">    private final static long WORKER_ID_BITS = 5L;</span><br><span class="line"></span><br><span class="line">    // 数据中心标识位数</span><br><span class="line">    private final static long DATA_CENTER_ID_BITS = 5L;</span><br><span class="line"></span><br><span class="line">    // 机器ID最大值 31</span><br><span class="line">    private final static long MAX_WORKER_ID = -1L ^ (-1L &lt;&lt; WORKER_ID_BITS);</span><br><span class="line"></span><br><span class="line">    // 数据中心ID最大值 31</span><br><span class="line">    private final static long MAX_DATA_CENTER_ID = -1L ^ (-1L &lt;&lt; DATA_CENTER_ID_BITS);</span><br><span class="line"></span><br><span class="line">    // 毫秒内自增位</span><br><span class="line">    private final static long SEQUENCE_BITS = 12L;</span><br><span class="line"></span><br><span class="line">    // 机器ID偏左移12位</span><br><span class="line">    private final static long WORKER_ID_SHIFT = SEQUENCE_BITS;</span><br><span class="line"></span><br><span class="line">    private final static long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;</span><br><span class="line"></span><br><span class="line">    // 时间毫秒左移22位</span><br><span class="line">    private final static long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS;</span><br><span class="line"></span><br><span class="line">    private final static long SEQUENCE_MASK = -1L ^ (-1L &lt;&lt; SEQUENCE_BITS);</span><br><span class="line"></span><br><span class="line">    private long lastTimestamp = -1L;</span><br><span class="line"></span><br><span class="line">    private long sequence = 0L;</span><br><span class="line">    private final long workerId;</span><br><span class="line">    private final long dataCenterId;</span><br><span class="line">    </span><br><span class="line">    @Override</span><br><span class="line">    public Queue&lt;String&gt; makeIds(int quantity) &#123;</span><br><span class="line">        Queue&lt;String&gt; ids = new LinkedBlockingQueue&lt;&gt;(quantity);</span><br><span class="line">        while (ids.size() &lt; quantity ) &#123;</span><br><span class="line">            ids.add(String.valueOf(nextId()));</span><br><span class="line">        &#125;</span><br><span class="line">        return ids;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 单例禁止new实例化</span><br><span class="line">     * @param workerId</span><br><span class="line">     * @param dataCenterId</span><br><span class="line">     */</span><br><span class="line">    public SnowFlakeStrategy() &#123;</span><br><span class="line">        </span><br><span class="line">//        String workerIdStr = SpringContextHolder.getEvnProperties(&quot;id.generator.workerId&quot;);</span><br><span class="line">        //第一次使用获取mac地址的</span><br><span class="line">        long workerIdLong = 0;</span><br><span class="line">        try &#123;</span><br><span class="line">            workerIdLong = getWorkerId();</span><br><span class="line">        &#125; catch (SocketException | UnknownHostException | NullPointerException e) &#123;</span><br><span class="line">            logger.error(&quot;获取机器ID失败&quot;, e);</span><br><span class="line">        &#125;</span><br><span class="line">        if (workerIdLong &gt; MAX_WORKER_ID || workerIdLong &lt;= 0) &#123;</span><br><span class="line">            workerId = getRandom();</span><br><span class="line">            </span><br><span class="line">        &#125;else &#123;</span><br><span class="line">            workerId = workerIdLong;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        String dataCenterIdStr = SpringContextHolder.getEvnProperties(&quot;id.generator.dataCenterId&quot;);</span><br><span class="line">        long dataCenterIdLong = 0;</span><br><span class="line">        if (dataCenterIdStr == null || !dataCenterIdStr.trim().matches(&quot;\\d+&quot;)) &#123;</span><br><span class="line">            logger.warn(String.format(&quot;数据中心ID配置异常，配置不能为空，而且必须位数字。数据中心Id：%s&quot;, dataCenterIdStr));</span><br><span class="line">            dataCenterIdLong = getRandom();</span><br><span class="line">        &#125;else &#123;</span><br><span class="line">            dataCenterIdLong = Long.valueOf(dataCenterIdStr.trim());</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        if (dataCenterIdLong &gt; MAX_DATA_CENTER_ID || dataCenterIdLong &lt;= 0) &#123;</span><br><span class="line">            logger.warn(String.format(&quot;%s 数据中心ID最大值 必须是 %d 到 %d 之间&quot;, dataCenterIdLong, 0, MAX_DATA_CENTER_ID));</span><br><span class="line">            dataCenterId = getRandom();</span><br><span class="line">        &#125;else &#123;</span><br><span class="line">            dataCenterId = dataCenterIdLong;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 生成1-31之间的随机数</span><br><span class="line">     *</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    private static long getRandom() &#123;</span><br><span class="line">        int max = (int) (MAX_WORKER_ID);</span><br><span class="line">        int min = 1;</span><br><span class="line">        Random random = new Random();</span><br><span class="line">        long result = random.nextInt(max - min) + min;</span><br><span class="line">        return result;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private long nextId() &#123;</span><br><span class="line">        long timestamp = time();</span><br><span class="line">        if (timestamp &lt; lastTimestamp) &#123;</span><br><span class="line">            throw new RuntimeException(&quot;时钟向后移动，拒绝生成id  &quot; + (lastTimestamp - timestamp) + &quot; milliseconds&quot;);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        if (lastTimestamp == timestamp) &#123;</span><br><span class="line">            // 当前毫秒内，则+1</span><br><span class="line">            sequence = (sequence + 1) &amp; SEQUENCE_MASK;</span><br><span class="line">            if (sequence == 0) &#123;</span><br><span class="line">                // 当前毫秒内计数满了，则等待下一秒</span><br><span class="line">                timestamp = tilNextMillis(lastTimestamp);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            sequence = 0;</span><br><span class="line">        &#125;</span><br><span class="line">        lastTimestamp = timestamp;</span><br><span class="line"></span><br><span class="line">        // ID偏移组合生成最终的ID，并返回ID</span><br><span class="line">        long nextId = ((timestamp - TWEPOCH) &lt;&lt; TIMESTAMP_LEFT_SHIFT)</span><br><span class="line">            | (dataCenterId &lt;&lt; DATA_CENTER_ID_SHIFT) | (workerId &lt;&lt; WORKER_ID_SHIFT) | sequence;</span><br><span class="line"></span><br><span class="line">        return nextId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private long tilNextMillis(final long lastTimestamp) &#123;</span><br><span class="line">        long timestamp = this.time();</span><br><span class="line">        while (timestamp &lt;= lastTimestamp) &#123;</span><br><span class="line">            timestamp = this.time();</span><br><span class="line">        &#125;</span><br><span class="line">        return timestamp;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private long time() &#123;</span><br><span class="line">        return System.currentTimeMillis();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private static long getWorkerId() throws SocketException, UnknownHostException, NullPointerException &#123;</span><br><span class="line">        @SuppressWarnings(&quot;unused&quot;)</span><br><span class="line">        InetAddress ip = InetAddress.getLocalHost();</span><br><span class="line"></span><br><span class="line">        NetworkInterface network = null;</span><br><span class="line">        Enumeration&lt;NetworkInterface&gt; en = NetworkInterface.getNetworkInterfaces();</span><br><span class="line">        while (en.hasMoreElements()) &#123;</span><br><span class="line">            NetworkInterface nint = en.nextElement();</span><br><span class="line">            if (!nint.isLoopback() &amp;&amp; nint.getHardwareAddress() != null) &#123;</span><br><span class="line">                network = nint;</span><br><span class="line">                break;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        byte[] mac = network.getHardwareAddress();</span><br><span class="line"></span><br><span class="line">        Random rnd = new Random();</span><br><span class="line">        byte rndByte = (byte) (rnd.nextInt() &amp; 0x000000FF);</span><br><span class="line"></span><br><span class="line">        // 取mac地址最后一位和随机数</span><br><span class="line">        return ((0x000000FF &amp; (long) mac[mac.length - 1]) | (0x0000FF00 &amp; (((long) rndByte) &lt;&lt; 8))) &gt;&gt; 6;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="流水号-自增Id-的规则策略实现"><a href="#流水号-自增Id-的规则策略实现" class="headerlink" title="流水号(自增Id)的规则策略实现"></a>流水号(自增Id)的规则策略实现</h2><p>对于自增的流水号，我们通过Redis的INCR命令，获取自增后的流水号。代码如下：   </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">public class AutoIncrementStrategy implements IdStrategy &#123;</span><br><span class="line">    </span><br><span class="line">    private StringRedisTemplate redisTemplate;</span><br><span class="line">    private String redisKey;</span><br><span class="line">    private String idType;</span><br><span class="line">    private int maxLength = 7; //流水号最大长度</span><br><span class="line"></span><br><span class="line">    public AutoIncrementStrategy(String idType) &#123;</span><br><span class="line">        this.idType = idType;</span><br><span class="line">        this.redisKey = String.format(&quot;%s-auto-increment&quot;, idType);</span><br><span class="line">        this.redisTemplate = SpringContextHolder.getBean(&quot;redisTemplate&quot;);</span><br><span class="line">        if (this.redisTemplate == null) &#123;</span><br><span class="line">            throw new RuntimeException(&quot;redis连接失败&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Queue&lt;String&gt; makeIds(int quantity) &#123;</span><br><span class="line">        Queue&lt;String&gt; ids = new LinkedBlockingQueue&lt;&gt;();</span><br><span class="line">        while (ids.size() &lt; quantity) &#123;</span><br><span class="line">            Long value = redisTemplate.opsForValue().increment(redisKey);</span><br><span class="line">            if (value == null) &#123;</span><br><span class="line">                throw new RuntimeException(String.format(&quot;获取编码失败，单据类型:%s&quot;, idType));</span><br><span class="line">            &#125;</span><br><span class="line">            </span><br><span class="line">            ids.offer(this.padding(String.valueOf(value), maxLength));</span><br><span class="line">        &#125;</span><br><span class="line">        return ids;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line">    private String padding(String value, int maxLength) &#123;</span><br><span class="line">        int valueLength = value.length();</span><br><span class="line">        int diff = maxLength - valueLength;</span><br><span class="line">        if (diff &lt; 0) &#123;</span><br><span class="line">            throw new RuntimeException(String.format(&quot;单据号已经超出最大长度,单据号:%s,最大长度：%s&quot;, value, maxLength));</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        StringBuffer stringBuffer = new StringBuffer();</span><br><span class="line">        for (int i = 0; i &lt; diff; i++) &#123;</span><br><span class="line">            stringBuffer.append(&quot;0&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        stringBuffer.append(value);</span><br><span class="line">        return stringBuffer.toString();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public String getIdType() &#123;</span><br><span class="line">        return this.idType;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="日期-流水号-自增Id-的规则策略实现"><a href="#日期-流水号-自增Id-的规则策略实现" class="headerlink" title="日期+流水号(自增Id)的规则策略实现"></a>日期+流水号(自增Id)的规则策略实现</h2><p>已流水号的生成为基础，加上日期作为前缀的实现日期加流水号的策略，代码如下：  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">public class DateIncrementStrategy extends AutoIncrementStrategy &#123;</span><br><span class="line">    </span><br><span class="line">    private static SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;yyyyMMddHHmmss&quot;);</span><br><span class="line"></span><br><span class="line">    public DateIncrementStrategy(String idType) &#123;</span><br><span class="line">        super(idType);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Queue&lt;String&gt; makeIds(int quantity) &#123;</span><br><span class="line">        String dateStr = dateFormat.format(new Date());</span><br><span class="line">        Queue&lt;String&gt; ids = super.makeIds(quantity);</span><br><span class="line">        if (ids == null || ids.size() != quantity) &#123;</span><br><span class="line">            throw new RuntimeException(String.format(&quot;获取编码失败，单据类型:%s&quot;, this.getIdType()));</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        return ids.stream().map(id-&gt;&#123;</span><br><span class="line">            return String.format(&quot;%s%s&quot;, dateStr, id);</span><br><span class="line">        &#125;).collect(Collectors.toCollection(LinkedHashSet::new));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="性能测试"><a href="#性能测试" class="headerlink" title="性能测试"></a>性能测试</h1><p>一款软件的发布必须保证满足性能需求，这通常需要在项目初期提出性能需求，在项目进行中做形成测试来验证。我是在自己的mac笔记本上面测试。CPU Intel I5 双核四线程，内存8G。测试方式采用嵌入式的方式，来测试，编写一个测试用例，启动 100个线程，共执行500万个请求。统计最终的测试数据，数据可能不是很准。但是也说明部分情况下性能。</p>
<h2 id="随机码的测试结果"><a href="#随机码的测试结果" class="headerlink" title="随机码的测试结果"></a>随机码的测试结果</h2><table>
<thead>
<tr>
<th>测试</th>
<th>测试1</th>
<th>测试2</th>
<th>测试3</th>
<th>测试4</th>
<th>测试5</th>
</tr>
</thead>
<tbody><tr>
<td>QPS</td>
<td>2110</td>
<td>2085</td>
<td>2336</td>
<td>2095</td>
<td>2561</td>
</tr>
<tr>
<td>平均时间(微秒)</td>
<td>473.92</td>
<td>479.46</td>
<td>428</td>
<td>477.36</td>
<td>390.5</td>
</tr>
<tr>
<td>最大响应时间(毫秒)</td>
<td>3889</td>
<td>3804</td>
<td>3815</td>
<td>3994</td>
<td>3233</td>
</tr>
</tbody></table>
<h2 id="流水号-自增Id-的测试结果"><a href="#流水号-自增Id-的测试结果" class="headerlink" title="流水号(自增Id)的测试结果"></a>流水号(自增Id)的测试结果</h2><table>
<thead>
<tr>
<th>测试</th>
<th>测试1</th>
<th>测试2</th>
<th>测试3</th>
<th>测试4</th>
<th>测试5</th>
</tr>
</thead>
<tbody><tr>
<td>QPS</td>
<td>233</td>
<td>224</td>
<td>251</td>
<td>216</td>
<td>239</td>
</tr>
<tr>
<td>平均时间(微秒)</td>
<td>4294</td>
<td>4459</td>
<td>3991</td>
<td>4619</td>
<td>4179</td>
</tr>
<tr>
<td>最大响应时间(毫秒)</td>
<td>681</td>
<td>868</td>
<td>696</td>
<td>631</td>
<td>810</td>
</tr>
</tbody></table>
<h2 id="日期-流水号-自增Id-的测试结果"><a href="#日期-流水号-自增Id-的测试结果" class="headerlink" title="日期+流水号(自增Id)的测试结果"></a>日期+流水号(自增Id)的测试结果</h2><table>
<thead>
<tr>
<th>测试</th>
<th>测试1</th>
<th>测试2</th>
<th>测试3</th>
<th>测试4</th>
<th>测试5</th>
</tr>
</thead>
<tbody><tr>
<td>QPS</td>
<td>229</td>
<td>231</td>
<td>238</td>
<td>217</td>
<td>242</td>
</tr>
<tr>
<td>平均时间(微秒)</td>
<td>4358.8</td>
<td>4334.6</td>
<td>4204.4</td>
<td>4600.6</td>
<td>4133.4</td>
</tr>
<tr>
<td>最大响应时间(毫秒)</td>
<td>648</td>
<td>574</td>
<td>628</td>
<td>698</td>
<td>637</td>
</tr>
</tbody></table>
<h2 id="流水号策略的性能过低，性能调优"><a href="#流水号策略的性能过低，性能调优" class="headerlink" title="流水号策略的性能过低，性能调优"></a>流水号策略的性能过低，性能调优</h2><p>从上面的数据看流水号的性能是在太低了，主要是每次获取都要到redis执行INCR命令，而且有锁的情况。因此进行一些性能优化。  </p>
<p>优化方式就是增加一个Queue缓存，每次从redis自增 1000，发号机就自己缓存1000个号码。每次取号，就先从缓存取，取不到再去redis里面取。这样其实就需要新增一个线程，用来写缓存，这个其实就用到多线程的生产者消费者模式，代码如下：</p>
<h2 id="流水号-自增Id-的优化后的代码"><a href="#流水号-自增Id-的优化后的代码" class="headerlink" title="流水号(自增Id)的优化后的代码"></a>流水号(自增Id)的优化后的代码</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自增策略(流水号策略)</span><br><span class="line"> * @author hzy</span><br><span class="line"> *</span><br><span class="line"> */</span><br><span class="line">public class AutoIncrementStrategy implements IdStrategy &#123;</span><br><span class="line">    </span><br><span class="line">    private static final Logger logger = LoggerFactory.getLogger(AutoIncrementStrategy.class);</span><br><span class="line">    private StringRedisTemplate redisTemplate;</span><br><span class="line">    private String redisKey;</span><br><span class="line">    private String idType;</span><br><span class="line">    private int maxLength = 7; //流水号最大长度</span><br><span class="line">    private int cacheLength; //缓存的容量 </span><br><span class="line">    LinkedBlockingQueue&lt;Long&gt; cache;</span><br><span class="line">    private Condition isWaitForFull;</span><br><span class="line">    private Condition isWaitForEmpty;</span><br><span class="line">    private AtomicInteger waitCount = new AtomicInteger();</span><br><span class="line">    ReentrantLock lock = new ReentrantLock();</span><br><span class="line">    </span><br><span class="line">    public AutoIncrementStrategy (String idType) &#123;</span><br><span class="line">        this(idType, 1000);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public AutoIncrementStrategy(String idType, int cacheLength) &#123;</span><br><span class="line">        this.idType = idType;</span><br><span class="line">        this.redisKey = String.format(&quot;%s-auto-increment&quot;, idType);</span><br><span class="line">        this.redisTemplate = SpringContextHolder.getBean(&quot;redisTemplate&quot;);</span><br><span class="line">        if (this.redisTemplate == null) &#123;</span><br><span class="line">            throw new RuntimeException(&quot;redis连接失败&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        this.cacheLength = cacheLength;</span><br><span class="line">        cache = new LinkedBlockingQueue&lt;&gt;();</span><br><span class="line">        </span><br><span class="line">        isWaitForFull = lock.newCondition();</span><br><span class="line">        isWaitForEmpty = lock.newCondition();</span><br><span class="line">        </span><br><span class="line">        Thread writeCacheThread = new Thread(new WriteCacheTask());</span><br><span class="line">        writeCacheThread.setName(&quot;AutoIncrementStrategy-write-cache-Thread&quot;);</span><br><span class="line">        writeCacheThread.start();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Queue&lt;String&gt; makeIds(int quantity) &#123;</span><br><span class="line">        Queue&lt;String&gt; ids = new LinkedBlockingQueue&lt;&gt;(quantity);</span><br><span class="line">        try &#123;</span><br><span class="line">            while (ids.size() &lt; quantity) &#123;</span><br><span class="line">                Long value = this.readFromCache();</span><br><span class="line">                ids.add(this.padding(String.valueOf(value), maxLength));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            throw new RuntimeException(e);</span><br><span class="line">        &#125;</span><br><span class="line">        return ids;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private Long readFromCache() &#123;</span><br><span class="line">        long t1 = System.currentTimeMillis();</span><br><span class="line">        Long value = null;</span><br><span class="line">        </span><br><span class="line">        while(value == null)&#123;</span><br><span class="line">            value = cache.poll();</span><br><span class="line">            </span><br><span class="line">            if (value == null) &#123;</span><br><span class="line">                logger.debug(&quot;没有拿到号，休息下&quot;);</span><br><span class="line">                try &#123;</span><br><span class="line">                    lock.lock();</span><br><span class="line">                    waitCount.incrementAndGet();</span><br><span class="line">                    isWaitForEmpty.signal();</span><br><span class="line">                    isWaitForFull.await(2, TimeUnit.SECONDS);</span><br><span class="line">                    </span><br><span class="line">                &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                    logger.error(&quot;等待拿号的过程中出现异常&quot;, e);</span><br><span class="line">                    throw new RuntimeException(e);</span><br><span class="line">                    </span><br><span class="line">                &#125;finally &#123;</span><br><span class="line">                    lock.unlock();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            </span><br><span class="line">            if (System.currentTimeMillis() - t1 &gt; 5000) &#123;</span><br><span class="line">                throw new RuntimeException(&quot;等待太久都没有拿到号&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        return value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private String padding(String value, int maxLength) &#123;</span><br><span class="line">        int valueLength = value.length();</span><br><span class="line">        int diff = maxLength - valueLength;</span><br><span class="line">        if (diff &lt; 0) &#123;</span><br><span class="line">            throw new RuntimeException(String.format(&quot;单据号已经超出最大长度,单据号:%s,最大长度：%s&quot;, value, maxLength));</span><br><span class="line">        &#125;</span><br><span class="line">    </span><br><span class="line">        StringBuffer stringBuffer = new StringBuffer();</span><br><span class="line">        for (int i = 0; i &lt; diff; i++) &#123;</span><br><span class="line">            stringBuffer.append(&quot;0&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        stringBuffer.append(value);</span><br><span class="line">        return stringBuffer.toString();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public String getIdType() &#123;</span><br><span class="line">        return this.idType;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    class WriteCacheTask implements Runnable&#123;</span><br><span class="line">        private boolean status = true;</span><br><span class="line">        </span><br><span class="line">        WriteCacheTask()&#123;</span><br><span class="line">            super();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        @Override</span><br><span class="line">        public void run() &#123;</span><br><span class="line">            logger.info(&quot;从redis获取自增编码的缓存写入开始&quot;);</span><br><span class="line">            while(status)&#123;</span><br><span class="line">                </span><br><span class="line">                if (!cache.isEmpty()) &#123;</span><br><span class="line">                    try &#123;</span><br><span class="line">                        lock.lock();</span><br><span class="line">                        isWaitForEmpty.await();</span><br><span class="line">                    &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                        logger.error(&quot;从redis获取自增编码的缓存写入异常&quot;, e);</span><br><span class="line">                    &#125;finally &#123;</span><br><span class="line">                        lock.unlock();</span><br><span class="line">                    &#125;</span><br><span class="line">                    </span><br><span class="line">                    continue;</span><br><span class="line">                &#125;</span><br><span class="line">                </span><br><span class="line">                lock.lock();</span><br><span class="line">                logger.debug(&quot;开始拿从reids拿号&quot;);</span><br><span class="line">                Long maxLong = redisTemplate.opsForValue().increment(AutoIncrementStrategy.this.redisKey, cacheLength);</span><br><span class="line">                </span><br><span class="line">                for(int i=0; i&lt;cacheLength; i++)&#123;</span><br><span class="line">                    cache.offer(maxLong - cacheLength + i + 1);</span><br><span class="line">                &#125;</span><br><span class="line">                logger.debug(&quot;拿到号并且缓存好了&quot;);</span><br><span class="line">                </span><br><span class="line">                if (waitCount.get() &gt; 0) &#123;</span><br><span class="line">                    isWaitForFull.signalAll();</span><br><span class="line">                &#125;</span><br><span class="line">                lock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">            logger.info(&quot;从redis获取自增编码的缓存写入结束&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="流水号-自增Id-的优化后的测试结果"><a href="#流水号-自增Id-的优化后的测试结果" class="headerlink" title="流水号(自增Id)的优化后的测试结果"></a>流水号(自增Id)的优化后的测试结果</h2><table>
<thead>
<tr>
<th>测试</th>
<th>测试1</th>
<th>测试2</th>
<th>测试3</th>
<th>测试4</th>
<th>测试5</th>
</tr>
</thead>
<tbody><tr>
<td>QPS</td>
<td>52670</td>
<td>55940</td>
<td>60016</td>
<td>62719</td>
<td>63427</td>
</tr>
<tr>
<td>平均时间(微秒)</td>
<td>1687</td>
<td>1747</td>
<td>1450</td>
<td>1372</td>
<td>1426</td>
</tr>
<tr>
<td>最大响应时间(毫秒)</td>
<td>2461</td>
<td>3969</td>
<td>2117</td>
<td>1956</td>
<td>2419</td>
</tr>
</tbody></table>
<h1 id="拓展思考"><a href="#拓展思考" class="headerlink" title="拓展思考"></a>拓展思考</h1><p>其实我们通过这个发号机的设计，拓展到理解数据库的ID生成策略，做一个流水号的单据规则，其实就类似与做数据库的自增ID。因此可以理解，数据库产生自增ID的时候，也会有一个自增ID锁，当并发大的时候也会有性能的问题。因此这也是我们建表的时候，尽量不使用自增ID，也是其中一个原因。   </p>
<p>但如果业务确实有需要用到自增ID，那么ID用完的时候，会出现什么问题，该怎么处理呢？  </p>
<p>当我们是用redis的INCR命令的时候，其实可以拓展做很多事情，例如做并发的控制，现在很多电商做抢购的控制，就是通过redis 的INCR命令控制。每当接受自动INCR增加，当增加的请求数超过库存就直接返回不在处理请求。  </p>
<p>或者通过redis的INCR做系统的幂等性控制，通过userId + 操作类型 作为key，通过过期时间，控制某些操作不能在限定的时间范围内重复操作。  </p>

    </div>

    
    
    
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/发号机-乐观锁-策略模式/" rel="tag"># 发号机 乐观锁 策略模式</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2019/09/25/Spring/" rel="next" title="Spring提供的事件驱动模型(观察者模式)">
                  <i class="fa fa-chevron-left"></i> Spring提供的事件驱动模型(观察者模式)
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2019/10/01/列出1小时内占用CPU最多的10个进程/" rel="prev" title="列出1小时内占用CPU最多的10个进程">
                  列出1小时内占用CPU最多的10个进程 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          
    
    <div class="comments" id="gitalk-container"></div>
  

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#需求分析"><span class="nav-number">1.</span> <span class="nav-text">需求分析</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#系统设计"><span class="nav-number">2.</span> <span class="nav-text">系统设计</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#具体实现"><span class="nav-number">3.</span> <span class="nav-text">具体实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#服务接口的定义"><span class="nav-number">3.1.</span> <span class="nav-text">服务接口的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#单据规则策略接口的定义"><span class="nav-number">3.2.</span> <span class="nav-text">单据规则策略接口的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#单据号规则的工厂类"><span class="nav-number">3.3.</span> <span class="nav-text">单据号规则的工厂类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#随机Id的规则策略实现"><span class="nav-number">3.4.</span> <span class="nav-text">随机Id的规则策略实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#雪花Id的规则策略实现"><span class="nav-number">3.5.</span> <span class="nav-text">雪花Id的规则策略实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#流水号-自增Id-的规则策略实现"><span class="nav-number">3.6.</span> <span class="nav-text">流水号(自增Id)的规则策略实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#日期-流水号-自增Id-的规则策略实现"><span class="nav-number">3.7.</span> <span class="nav-text">日期+流水号(自增Id)的规则策略实现</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#性能测试"><span class="nav-number">4.</span> <span class="nav-text">性能测试</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#随机码的测试结果"><span class="nav-number">4.1.</span> <span class="nav-text">随机码的测试结果</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#流水号-自增Id-的测试结果"><span class="nav-number">4.2.</span> <span class="nav-text">流水号(自增Id)的测试结果</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#日期-流水号-自增Id-的测试结果"><span class="nav-number">4.3.</span> <span class="nav-text">日期+流水号(自增Id)的测试结果</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#流水号策略的性能过低，性能调优"><span class="nav-number">4.4.</span> <span class="nav-text">流水号策略的性能过低，性能调优</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#流水号-自增Id-的优化后的代码"><span class="nav-number">4.5.</span> <span class="nav-text">流水号(自增Id)的优化后的代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#流水号-自增Id-的优化后的测试结果"><span class="nav-number">4.6.</span> <span class="nav-text">流水号(自增Id)的优化后的测试结果</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#拓展思考"><span class="nav-number">5.</span> <span class="nav-text">拓展思考</span></a></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Jimmy Wong</p>
  <div class="site-description" itemprop="description"></div>
</div>
  <nav class="site-state motion-element">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">12</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span>
        
      </div>
    
  </nav>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jimmy Wong</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.9.0</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.4.0</div>

        












        
      </div>
    </footer>
  </div>

  


  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  





















  

  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID: '1e03a8c2c942a007aa2d',
      clientSecret: 'c13db1d348fcbb2f0151ed1472c95119b9b34445',
      repo: 'blog-comment',
      owner: 'hzy2009',
      admin: ['hzy2009'],
      id: '79d3baae81fb52b606388f5b5580c05d',
        language: 'zh-CN',
      
      distractionFreeMode: 'true'
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
</script>

</body>
</html>
